package com.demo.gateway.routes;

import static com.demo.gateway.routes.GatewayConstant.GATEWAY_REDIS_ROUTES;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.demo.gateway.pojo.GatewayRouteDO;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author: demo
 * @date: 2020年6月17日
 * @Document : redis 路由存储类
 */
@Slf4j
@Repository
public class RedisRouteRepository implements RouteDefinitionRepository {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * 允许访问路由状态
	 */
	public  final  static  Integer  ALLOW_ROUTE_STATUS=1;

	/**
	 * 获得所有redis routes
	 */
	@Override
	public Flux<RouteDefinition> getRouteDefinitions() {
		BoundHashOperations<String, String, String> boundHashOperations = redisTemplate
				.boundHashOps(GATEWAY_REDIS_ROUTES.name());
		Map<String, String> redisRoutes = boundHashOperations.entries();
		List<RouteDefinition> gatewayRoutes = new ArrayList<RouteDefinition>();
		int  allowRoute = 0;
		for (String routeKey : redisRoutes.keySet()) {
			String routeInfo = redisRoutes.get(routeKey);
			RouteDefinition routeDefinition = JSON.parseObject(routeInfo, RouteDefinition.class);
			GatewayRouteDO gatewayRouteDefinition = JSON.parseObject(routeInfo, GatewayRouteDO.class);
			if (ALLOW_ROUTE_STATUS.equals(gatewayRouteDefinition.getStatus())) {
				gatewayRoutes.add(routeDefinition);
				allowRoute++;
			}
		}
		int  totalRoute=redisRoutes.keySet().size();
		log.info("获取redis所有RoutesCount：{} ,允许访问routeCount==>{} ,禁止访问routeCount==>{}", totalRoute,allowRoute,totalRoute-allowRoute);
		return Flux.fromIterable(gatewayRoutes);

	}

	/**
	 * 保存
	 */
	@Override
	public Mono<Void> save(Mono<RouteDefinition> route) {
		return Mono.empty();
	}

	/**
	 * 删除
	 */
	@Override
	public Mono<Void> delete(Mono<String> routeId) {
		return Mono.empty();
	}

}
